<?php
/**
 * 邮储食堂
 * User: cxm
 * Date: 2020/12/7
 * Time: 10:27
 */
namespace App\Http\Controllers\Home;
use App\Models\RegularUserApply;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class FoodsController extends Controller {
    /**
     * 申请为正式会员
     * URL POST:/api/home/foods/apply
     * @param Request $request
     * @param string name 姓名
     * @param string mobile 联系电话
     * @param int is_card 是否已办工会卡 1是2否
     * @param int is_food 是否办理邮储食堂卡 1是2否
     * @return mixed
     */
    public function apply(Request $request){
        $params = $request->only(['name','mobile','is_card','is_food']);
        $validator = Validator::make($params,[
            'name'              => ['required'],
            'mobile'            => ['required','regex:/^1[3456789]\d{9}$/'],
            'is_card'           => ['required','in:1,2'],
            //'is_food'           => ['required','in:1,2']
        ],[
            'name.required'             => '请输入姓名',
            'mobile.required'           => '请输入手机',
            'mobile.regex'              => '请输入联系电话',
            'is_card.required'          => '请选择是否已办工会卡',
            'is_card.in'                => '是否已办工会卡只能选择是或者否',
            //'is_food.required'          => '请选择是否办理邮储食堂卡',
            //'is_food.in'                => '是否办理邮储食堂卡只能选择是或者否'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 用户信息
        $user = $this->userModel();
        DB::beginTransaction();
        try {
            $apply = new RegularUserApply();
            $apply->user_id             = $user['id'];
            $apply->name                = $params['name'];
            $apply->mobile              = $params['mobile'];
            $apply->is_card             = $params['is_card'];
            $apply->is_food             = isset($params['is_food']) ? $params['is_food']: 2;
            $apply->save();
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

}